<template>
  <div class="mobile-maintenance">
    <!-- 顶部导航 -->
    <MobileHeader />

    <!-- 统计卡片 -->
    <StatsCards :stats="stats" @card-click="handleStatsCardClick" />

    <!-- 标签页切换 -->
    <TabBar :active-tab="activeTab" @tab-change="handleTabChange" />

    <!-- 工单列表 -->
    <WorkOrderList 
      :orders="filteredOrders" 
      :loading="loading"
      :current-user-id="authStore.user?.id"
      @view-detail="viewOrderDetail"
      @accept-order="handleAcceptOrder"
      @show-feedback="showFeedbackDialog"
      @show-complete="showCompleteDialog"
      @edit-order="editOrder"
    />

    <!-- 反馈对话框 -->
    <FeedbackDialog 
      v-model:visible="feedbackDialogVisible"
      :work-order-id="currentWorkOrderId"
      @submit="handleFeedbackSubmit"
    />

    <!-- 回单对话框 -->
    <CompleteDialog 
      v-model:visible="completeDialogVisible"
      :work-order-id="currentWorkOrderId"
      :available-materials="availableMaterials"
      @submit="handleCompleteSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores/auth'

// 导入组件
import MobileHeader from '@/components/mobile/MobileHeader.vue'
import StatsCards from '@/components/mobile/StatsCards.vue'
import TabBar from '@/components/mobile/TabBar.vue'
import WorkOrderList from '@/components/mobile/WorkOrderList.vue'
import FeedbackDialog from '@/components/mobile/FeedbackDialog.vue'
import CompleteDialog from '@/components/mobile/CompleteDialog.vue'

// 导入组合式函数
import { useWorkOrders, type WorkOrder } from '@/composables/useWorkOrders'
import { useMaterials } from '@/composables/useMaterials'
import { useWorkOrderActions, type FeedbackForm, type CompleteForm } from '@/composables/useWorkOrderActions'

const router = useRouter()
const authStore = useAuthStore()

// 使用组合式函数
const { loading, stats, loadWorkOrders, getFilteredOrders, acceptOrder } = useWorkOrders()
const { availableMaterials, loadMaterials } = useMaterials()
const { submitFeedback, submitComplete } = useWorkOrderActions()

// 响应式数据
const activeTab = ref('pending')
const feedbackDialogVisible = ref(false)
const completeDialogVisible = ref(false)
const currentWorkOrderId = ref<number | null>(null)

// 计算属性
const filteredOrders = computed(() => {
  return getFilteredOrders(activeTab.value)
})

// 事件处理方法
const handleTabChange = (tab: string) => {
  activeTab.value = tab
  // 不需要重新加载数据，只需要切换显示的工单类型
  // 所有工单数据已经在初始化时加载完成
}

const handleAcceptOrder = async (order: WorkOrder) => {
  try {
    await ElMessageBox.confirm('确定要接受这个工单吗？', '确认接单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    await acceptOrder(order)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('接单确认失败:', error)
    }
  }
}

const showFeedbackDialog = (order: WorkOrder) => {
  currentWorkOrderId.value = order.id
  feedbackDialogVisible.value = true
}

const showCompleteDialog = (order: WorkOrder) => {
  currentWorkOrderId.value = order.id
  completeDialogVisible.value = true
}

const handleFeedbackSubmit = async (form: FeedbackForm) => {
  try {
    await submitFeedback(form)
    feedbackDialogVisible.value = false
    // 重新加载所有工单数据以获取最新状态
    await loadWorkOrders()
  } catch (error) {
    // 错误处理已在组合式函数中完成
  }
}

const handleCompleteSubmit = async (form: CompleteForm) => {
  try {
    await submitComplete(form)
    completeDialogVisible.value = false
    // 重新加载所有工单数据以获取最新状态
    await loadWorkOrders()
  } catch (error) {
    // 错误处理已在组合式函数中完成
  }
}

const viewOrderDetail = (order: WorkOrder) => {
  router.push(`/mobile/work-orders/${order.id}`)
}

const editOrder = (order: WorkOrder) => {
  router.push(`/mobile/work-orders/${order.id}/edit`)
}

const handleStatsCardClick = (status: string) => {
  // 直接切换标签页，不需要重新加载数据
  switch (status) {
    case 'pending':
      activeTab.value = 'pending'
      break
    case 'processing':
      activeTab.value = 'processing'
      break
    case 'completed':
      activeTab.value = 'completed'
      break
  }
}

// 生命周期
onMounted(() => {
  // 加载所有状态的工单数据
  loadWorkOrders()
  loadMaterials()
})
</script>

<style scoped>
.mobile-maintenance {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 20px;
}
</style>